package com.sxpi.zixun.aspect.auth;

import com.sxpi.zixun.common.enums.AdminUserResultEnum;
import com.sxpi.zixun.common.ex.PugValidatorException;
import com.sxpi.zixun.local.UserThreadLocal;
import com.sxpi.zixun.pojo.AdminUser;
import com.sxpi.zixun.service.adminuser.IAdminUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

/**
 * @Author: 董伟豪
 * @Date: 2022/8/29 12:44
 */
@Aspect
@Component
@Slf4j
@RequiredArgsConstructor
public class PermissionAspect {

    private final IAdminUserService adminUserService;

    @Pointcut("@annotation(com.sxpi.zixun.aspect.auth.HasAuth)")
    public void pointCut(){

    }

    @Before("pointCut()")
    public void beforeAdvice(JoinPoint joinPoint){
        // 获取签名
        MethodSignature signature = (MethodSignature)joinPoint.getSignature();
        // 获取执行的方法
        Method method = signature.getMethod();
        // 获取方法的注解
        HasAuth annotation = method.getAnnotation(HasAuth.class);
        // 获取权限代号
        String[] valueCodes = annotation.value();
        // 然后根据登录的用户去获取对应的权限信息
        AdminUser adminUser = UserThreadLocal.get();
        // 查询出用户所有的权限信息 追求实时
        List<String> byUserPermission = adminUserService.findByUserPermission(adminUser.getId());
        // 取交集
        Collection intersection = CollectionUtils.intersection(Arrays.asList(valueCodes), byUserPermission);
        // 如果没有权限直接抛出异常
        if(CollectionUtils.isEmpty(intersection)){
            throw new PugValidatorException(AdminUserResultEnum.USER_ROLE_AUTH_ERROR);
        }

    }
}
